<template>
    <div class="page-content">
        <div style="background-color: #FFFFFF; padding-bottom: 10px;">
            <view class="goods-list" style="height: 120px; display: flex; margin-bottom: 6px;"
                  v-for="(item, index) in tbGoodsList" :key="index">

                <view @click.stop.prevent="gotoGoodsDetail(item)">
                    <image style="height: 100px; width: 100px; padding-top: 4px;"
                           :src="item.thumbnailUrl ? item.thumbnailUrl + '?imageView2/1/w/300/h/300' : '/static/default-image/goods.jpg'"
                           mode="aspectFill"></image>
                </view>
                <view style="padding: 6px 5px 5px 10px; width: 100%;" @click.stop.prevent="gotoGoodsDetail(item)">
                    <view style="height: 60px; overflow: hidden; padding-top: 5px;">
                        {{item.title}}
                    </view>
                    <view style="overflow: hidden; color: grey; height: 19px;">
                        {{item.subTitle | toEmptyStr}}
                    </view>
                    <view style="text-align: right; padding-bottom: 2px;" v-if="item.countDown && !item.countDownEnd">
                        <label>
                            <u-count-down separator="zh" :key="item.id" :timestamp="item.countDown"
                                          @end="updateSeckillStatus([item])"></u-count-down>
                        </label>
                    </view>
                    <view style="display: flex; border-bottom: 1px solid #eeeeee; padding-bottom: 4px;"
                          :style="{'border-bottom': tbGoodsList.length - 1 === index ? '0px' : '1px solid #eeeeee'}">
                        <view style="font-weight: bold; color: red; width: 100%;">
                            ￥{{item.price | toFixed2}}
                        </view>
                        <view>
                            <u-button type="error" size="mini" @click="seckillGoods(item)" :disabled="item.disabled">{{item.seckillStatusText}}</u-button>
                        </view>
                    </view>
                </view>
            </view>
        </div>

        <div style="padding-top: 10px; padding-bottom: 10px;" v-if="tbGoodsList.length">
            <u-loadmore :status="pagination.status" bg-color="#eeeeee"/>
        </div>

        <div style="padding-top: 10px; padding-bottom: 10px; text-align: center;" v-if="!tbGoodsList.length">
            没有正在秒杀的商品
        </div>
    </div>
</template>

<script>
    import {CommonUtil} from "../dev/core/utils/common.util";
    import {TbSeckillGoodsService} from "../dev/services/tb-seckill-goods.service";

    export default {
        props: ["storeId"],
        data: function () {
            return {
                tbGoodsList: [],
            }
        },
        components: {},
        created() {
            this.doInfinite();
        },
        methods: {
            gotoGoodsDetail(item) {
                console.log(item);
                uni.navigateTo({
                    url: `/pages/common/goods-detail/index?${CommonUtil.objectToUrlParams(item)}`
                })
            },
            doInfinite() {
                const _self = this;
                new TbSeckillGoodsService().findTableListByConsumer({
                    pagination: _self.pagination,
                    data: {
                        communityId: _self.globalVariable.userInfo.tbCommunity.id,
                        storeId: _self.storeId,
                        orderBy: 'showorder asc'
                    }
                }).then(result => {
                    _self.pagination.refreshPage(result);
                    _self.tbGoodsList = [..._self.tbGoodsList, ...result.list];
                    _self.updateSeckillStatus(_self.tbGoodsList);
                })
            },
            updateSeckillStatus(tbGoodsList) {
                const _self = this;
                console.log(tbGoodsList);
                tbGoodsList.forEach((item, index) => {
                    if (new Date().getTime() < new Date(item.startTime).getTime()) {
                        item.disabled = true;
                        item.seckillStatusText = '未开始';
                        item.countDown = new Date(item.startTime).getTime() / 1000 - new Date().getTime() / 1000;
                        item.countDownEnd = false;  // 是否结束倒计时
                    } else if (new Date().getTime() > new Date(item.endTime).getTime()) {
                        item.disabled = true;
                        item.seckillStatusText = '已结束';
                        item.countDownEnd = true;
                    } else {
                        item.disabled = false;
                        item.seckillStatusText = '立即秒杀';
                        item.countDown = new Date(item.endTime).getTime() / 1000 - new Date().getTime() / 1000;
                        item.countDownEnd = false;
                    }
                });
                _self.$forceUpdate();
            },
            /**
             * 添加秒杀商品
             */
            seckillGoods(item) {
                const _self = this;
                uni.showLoading({
                    title: '秒杀中'
                });
                new TbSeckillGoodsService().seckillGoods(item.seckillGoodsId).then(result => {
                    if (result.status === "success") {
                        uni.showLoading({
                            title: '秒杀中'
                        });

                        // 排队中，查询秒杀结果
                        _self.findSeckillResult(item.seckillGoodsId);
                    } else {
                        uni.hideLoading();
                        CommonUtil.alert(result.message);
                    }
                })
            },
            /**
             * result = seckillOrderId：成功， result = -1：秒杀失败， result = 0： 排队中
             * @param seckillGoodsId
             */
            findSeckillResult(seckillGoodsId) {
                const _self = this;
                new TbSeckillGoodsService().findSeckillResult(seckillGoodsId).then(result => {
                    if (result.data === "-1") {
                        uni.hideLoading();
                        CommonUtil.alert("商品已秒杀光");
                    } else if (result.data === "0") {  // 排队中，则轮询查询秒杀结果
                        setTimeout(() => {
                            _self.findSeckillResult(seckillGoodsId);
                        }, 100);
                    } else {
                        uni.hideLoading();
                        let tbSeckillOrder = result.data;
                        CommonUtil.alert({
                            title: '提示！',
                            content: '恭喜您，秒杀成功！查看订单？',
                            showCancel: true, // 是否显示取消按钮
                            success: function (res) {
                                if (res.cancel) { // 点击取消,默认隐藏弹框
                                } else { // 点击确定
                                    if (tbSeckillOrder.saleMode === '0') { // 物流模式
                                        uni.navigateTo({
                                            url: `/pages/sub/sub1-tabs/tabs/person/order/order-detail/index?id=${tbSeckillOrder.orderId}`
                                        })
                                    } else if (tbSeckillOrder.saleMode === '1') { // 消费券模式
                                        uni.navigateTo({
                                            url: `/pages/sub/sub1-tabs/tabs/person/consumer-voucher/consumer-voucher-detail/index?id=${tbSeckillOrder.orderId}`
                                        })
                                    } else if (tbSeckillOrder.saleMode === '2') { // 餐饮店模式
                                        uni.navigateTo({
                                            url: `/pages/sub/sub1-tabs/tabs/person/eatery-order/eatery-order-detail/index?id=${tbSeckillOrder.orderId}`
                                        })
                                    }
                                }
                            }
                        });
                    }
                })
            }
        },
    }
</script>

<style lang="scss" scoped>
</style>
